package com.xzcs.controller.tools;

import com.github.pagehelper.PageInfo;
import com.xzcs.controller.BaseController;
import com.xzcs.service.tools.GeneratorService;
import com.xzcs.util.web.ResponseUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;


/**
 * 代码生成
 * @author chang
 * @createDate 2015-6-23
 */
@Controller
@RequestMapping(value = "/systools/generator/")
public class GeneratorController extends BaseController {
	
	@Autowired
	private GeneratorService generatorService;
	
	@RequestMapping(value = "frame.do")
	public String frame(HttpServletRequest request) {
		return "html/tools/generator/frame";
	}
	
	@RequestMapping(value = "list.do")
	public void list(HttpServletRequest request, HttpServletResponse response) {
		PageInfo<Map<String, Object>> page = generatorService.findTables(request);
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("total", page.getTotal());
		result.put("rows", page.getList());
		ResponseUtils.writeJson(result, response);
	}

	@RequestMapping(value = "generatorCode.do")
	public void generatorCode(HttpServletRequest request, HttpServletResponse response) {
		try {
			byte[] data = generatorService.generatorCode(request);
			response.reset();
			response.setHeader("Content-Disposition", "attachment; filename=\"code.zip\"");
			response.addHeader("Content-Length", "" + data.length);
			response.setContentType("application/octet-stream; charset=UTF-8");
			IOUtils.write(data, response.getOutputStream());
		} catch (Exception e) {
			logger.error("代码生成错误：", e);
		}
	}
}
